package com.example.homeworkmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.homeworkmanagement.dto.NotificationsAndClassesTeachersDTO;
import com.example.homeworkmanagement.pojo.Classes;
import com.example.homeworkmanagement.pojo.Notifications;
import com.example.homeworkmanagement.mapper.NotificationsMapper;
import com.example.homeworkmanagement.pojo.Teachers;
import com.example.homeworkmanagement.service.ClassesService;
import com.example.homeworkmanagement.service.NotificationsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.homeworkmanagement.service.TeachersService;
import com.example.homeworkmanagement.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 拒绝加班
 * @since 2025-05-25
 */
@Service
public class NotificationsServiceImpl extends ServiceImpl<NotificationsMapper, Notifications> implements NotificationsService {
    @Autowired
    private NotificationsMapper notificationsMapper;
    @Autowired
    private TeachersService teachersService;

    @Autowired
    private ClassesService classesService;

    @Override
    public ResultVO<Notifications> saveNotification(Notifications notifications,String classNames) {
        try {
            if (notifications.getTeacherId() == null || notifications.getTeacherId().isEmpty()) {
                return ResultVO.fail("teacher_id不能为空");
            }
            if (notifications.getTitle() == null || notifications.getTitle().isEmpty()) {
                return ResultVO.fail("title不能为空");
            }
            if (notifications.getContent() == null || notifications.getContent().isEmpty()) {
                return ResultVO.fail("content不能为空");
            }
            if (notifications.getPublishTime() == null) {
                notifications.setPublishTime(new Date());
            }

            if(classNames==null || classNames.trim().isEmpty()){
                return ResultVO.fail("班级名称不能为空");
            }
            String[] classesArray = classNames.split("[、,| ，]");
            List<String> classes = new ArrayList<>(Arrays.asList(classesArray));
            System.out.println(classes);
            ResultVO<String> resultVO = classesService.getClassIdsByNames(classes);
            String classIds = resultVO.getResult();
            notifications.setClassIds(classIds);
            boolean saveSuccess = this.save(notifications);
            if (!saveSuccess) {
                return ResultVO.fail("通知添加失败");
            }
            return ResultVO.success("通知添加成功", notifications);
        } catch (Exception e) {
            return ResultVO.fail("添加通知时发生异常：" + e.getMessage());
        }
    }


    @Override
    public ResultVO<Notifications> removeNotificationById(Integer notificationId) {
        try {
            // 检查通知是否存在
            Notifications existingNotification = this.getOne(new QueryWrapper<Notifications>().eq("notification_id", notificationId));
            if (existingNotification == null) {
                return ResultVO.fail("通知id不存在");
            }
            boolean deleteSuccess = this.removeById(notificationId);
            if (!deleteSuccess) {
                return ResultVO.fail("通知删除失败");
            }
            return ResultVO.success("通知删除成功");
        } catch (Exception e) {
            return ResultVO.fail("删除通知时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Notifications> getNotificationById(Integer notificationId) {
        try {
            Notifications notification = this.getOne(new QueryWrapper<Notifications>().eq("notification_id", notificationId));
            if (notification == null) {
                return ResultVO.fail("通知id不存在");
            }
            return ResultVO.success("通知详情获取成功", notification);
        } catch (Exception e) {
            return ResultVO.fail("获取通知详情时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Notifications> updateNotification(Notifications notifications,String classNames) {
        try {
            // 检查通知是否存在
            Notifications existingNotification = this.getOne(new QueryWrapper<Notifications>().eq("notification_id", notifications.getNotificationId()));
            if (existingNotification == null) {
                return ResultVO.fail("通知id不存在");
            }
            // 更新字段（只更新非空值且非空字符串）
            String classIds = notifications.getClassIds();
            if (classIds != null &&!classIds.trim().isEmpty()) {
                existingNotification.setClassIds(classIds);
            }
            String title = notifications.getTitle();
            if (title != null &&!title.trim().isEmpty()) {
                existingNotification.setTitle(title);
            }
            String content = notifications.getContent();
            if (content != null &&!content.trim().isEmpty()) {
                existingNotification.setContent(content);
            }
            java.util.Date publishTime = notifications.getPublishTime();
            existingNotification.setPublishTime(new Date());
            if(classNames!=null || !classNames.trim().isEmpty()){
                String[] classesArray = classNames.split("[、,| ，]");
                List<String> classes = new ArrayList<>(Arrays.asList(classesArray));
                System.out.println(classes);
                ResultVO<String> resultVO = classesService.getClassIdsByNames(classes);
                String classIds1 = resultVO.getResult();
                existingNotification.setClassIds(classIds1);
            }
            boolean updateSuccess = this.updateById(existingNotification);
            if (!updateSuccess) {
                return ResultVO.fail("通知信息更新失败");
            }
            return ResultVO.success("通知信息更新成功", existingNotification);
        } catch (Exception e) {
            return ResultVO.fail("更新通知时发生异常：" + e.getMessage());
        }
    }
    @Override
    public ResultVO<List<NotificationsAndClassesTeachersDTO>> getNotificationList(
            Notifications notifications,
            String className,
            String teacherName,
            int page,
            int size) {
        QueryWrapper<Notifications> queryWrapper = new QueryWrapper<>();

        if (notifications.getTitle() != null && !notifications.getTitle().isEmpty()) {
            queryWrapper.like("title", notifications.getTitle());
        }

        if (notifications.getContent() != null && !notifications.getContent().isEmpty()) {
            queryWrapper.like("content", notifications.getContent());
        }

        if (notifications.getTeacherId() != null && !notifications.getTeacherId().isEmpty()) {
            queryWrapper.eq("teacher_id", notifications.getTeacherId());
        }

        if (notifications.getClassIds() != null && !notifications.getClassIds().isEmpty()) {
            queryWrapper.like("class_ids", notifications.getClassIds());
        }

        if (teacherName != null && !teacherName.trim().isEmpty()) {
            ResultVO<List<String>> resultVO = teachersService.selectByTeacherName(teacherName);
            if(resultVO.isFlag()==false){
                return ResultVO.fail("未查询到信息");
            }
            List<String> teacherIdList = resultVO.getResult();
            if(teacherIdList!=null || !teacherIdList.isEmpty()){
                Set<String> teacherIdSet = new HashSet<>(teacherIdList);
                if (!teacherIdSet.isEmpty()) {
                    queryWrapper.in("teacher_id", teacherIdSet);
                }
            }
        }

        if (notifications.getPublishTime() != null) {
            queryWrapper.le("publish_time",notifications.getPublishTime());
        }

        if (className != null && !className.trim().isEmpty()) {
            ResultVO<List<String>> resultVO = classesService.getClassIdsByName(className);
            if(resultVO.isFlag()==false){
                return ResultVO.fail("未查询到信息");
            }
            List<String> classIdsList = resultVO.getResult();
            if (classIdsList != null && !classIdsList.isEmpty()) {
                String commonPrefix = classIdsList.get(0);
                for (int i = 1; i < classIdsList.size(); i++) {
                    while (!classIdsList.get(i).startsWith(commonPrefix)) {
                        commonPrefix = commonPrefix.substring(0, commonPrefix.length() - 1);
                    }
                }
                if (!commonPrefix.isEmpty()) {
                    queryWrapper.like("class_ids", commonPrefix);
                }
            }
        }

        //获取总数
        List<Notifications> listSize = this.list(queryWrapper);
        int total = listSize.size();

        Page<Notifications> pageResult = this.page(new Page<>(page, size), queryWrapper);
        if(pageResult.getRecords()==null || pageResult.getRecords().isEmpty()){
            return ResultVO.fail("未查询到信息");
        }
        List<Notifications> list = pageResult.getRecords();

        List<NotificationsAndClassesTeachersDTO> list1 = new ArrayList<>();
        for (Notifications notifications1 : list) {
            NotificationsAndClassesTeachersDTO dto = new NotificationsAndClassesTeachersDTO();
            dto.setClassIds(notifications1.getClassIds());
            dto.setTitle(notifications1.getTitle());
            dto.setContent(notifications1.getContent());
            dto.setNotificationId(notifications1.getNotificationId());
            dto.setPublishTime(notifications1.getPublishTime());
            dto.setTeacherId(notifications1.getTeacherId());

            ResultVO<String> resultVO = classesService.getClassNamesByIds(notifications1.getClassIds());
            if (resultVO != null && resultVO.getResult() != null) {
                dto.setClassNames(resultVO.getResult());
            }

            ResultVO<Teachers> teachersResultVO = teachersService.getTeacherDetail(notifications1.getTeacherId());
            if (teachersResultVO != null && teachersResultVO.getResult() != null) {
                dto.setTeacherName(teachersResultVO.getResult().getTeacherName());
            }
            list1.add(dto);
        }

        return ResultVO.success("通知列表获取成功", list1, total);
    }
}
